home *** CD-ROM | disk | FTP | other *** search
/ The Very Best of Atari Inside / The Very Best of Atari Inside 1.iso / mint / mntlib25 / mntlib25.zoo / fdopen.c < prev    next >
C/C++ Source or Header  |  1992-08-26  |  1KB  |  70 lines

  1. /* from Dale Schumacher's dLibs */
  2.  
  3. #include <stdio.h>
  4. #include <fcntl.h>
  5. #include <unistd.h>
  6. #include <errno.h>
  7.  
  8. FILE *fdopen(h, mode)
  9.     register int h;
  10.     const register char *mode;
  11. {
  12.     extern int __default_mode__;    /* see defmode.c */
  13.     register int i, iomode = 0, f = __default_mode__;
  14.     register FILE *fp = NULL;
  15.     void _getbuf __PROTO((FILE *));
  16.  
  17.     for(i=0; (!fp && (i < _NFILE)); ++i)
  18.         if(!(_iob[i]._flag & (_IORW | _IOREAD | _IOWRT)))
  19.             fp = &_iob[i];    /* empty slot */
  20.     if(!fp) {
  21.         errno = EMFILE;
  22.         return(NULL);
  23.     }
  24.  
  25.     while(*mode) {
  26.         switch(*mode++) {
  27.             case 'r':
  28.                 f |= _IOREAD;
  29.                 break;
  30.             case 'w':
  31.                 f |= _IOWRT;
  32.                 iomode |= (O_CREAT | O_TRUNC);
  33.                 break;
  34.             case 'a':
  35.                 f |= _IOWRT;
  36.                 iomode |= (O_CREAT | O_APPEND);
  37.                 break;
  38.             case '+':
  39.                 f &= ~(_IOREAD | _IOWRT);
  40.                 f |= _IORW;
  41.                 break;
  42.             case 'b':
  43.                 f |= _IOBIN;
  44.                 break;
  45.             case 't':
  46.                 f &= ~_IOBIN;
  47.                 break;
  48.             default:        /* illegal file mode */
  49.                 return(NULL);
  50.             }
  51.     }
  52.     if((i = (f & (_IORW | _IOREAD | _IOWRT))) == 0)
  53.         return(NULL);
  54.     else if(i == _IOREAD)
  55.         iomode |= O_RDONLY;
  56.     else if(i == _IOWRT)
  57.         iomode |= O_WRONLY;
  58.     else
  59.         iomode |= O_RDWR;
  60.  
  61.     if(isatty(h))
  62.         f |= (_IODEV | _IONBF);
  63.     else
  64.         f |= _IOFBF;
  65.     fp->_file = h;            /* file handle */
  66.     fp->_flag = f;            /* file status flags */
  67.     _getbuf(fp);
  68.     return(fp);
  69. }
  70.